<template>
  <div class="goodsCredential">
    <el-card>
      <template #header>
        <el-icon><Tickets /></el-icon>
        <span>商品资质</span>
      </template>
      <template #default>
        <div class="upload_pic_btn_box">
          <div>已选择 <span class="upload_pic_number">{{getCredentialNum()}}</span><span>/5</span> 张资质图片</div>
          <el-button v-if="form.attach" icon="Plus" class="upload_pic_btn_style" @click="toChooseCredential">重新选择资质</el-button>
        </div>
        <div class="upload_pic_tips_box">
          <div v-if="!form.attach" class="upload_pic_tips" @click="toChooseCredential">
            <svg t="1693876723403" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4286" width="120" height="120"><path d="M447.829333 754.176 447.829333 695.978667 224.938667 695.978667 224.938667 754.176Z" p-id="4287" fill="#DFDFDF"></path><path d="M447.829333 593.237333 447.829333 535.210667 224.938667 535.210667 224.938667 593.237333Z" p-id="4288" fill="#DFDFDF"></path><path d="M961.194667 900.266667c3.242667-4.096 3.584-9.728 1.365333-14.336l-101.034667-188.416c10.922667-24.405333 16.896-49.322667 16.896-76.117333 0.512-102.229333-82.090667-185.344-184.490667-185.685333-0.341333 0-0.512 0-0.853333 0-101.888 0-184.661333 82.432-184.832 184.32-0.170667 25.770667 5.290667 51.370667 16.213333 75.946667l0.853333 1.877333-102.912 186.197333c-2.389333 4.437333-2.218667 10.24 1.024 14.336 3.072 4.096 8.362667 5.973333 13.312 4.949333l89.941333-20.309333 30.549333 85.845333c1.706667 4.778667 5.973333 8.192 11.093333 8.704 0.341333 0 0.512 0 0.853333 0l0.170667 0c5.12 0 9.557333-2.56 11.776-6.826667l90.453333-167.082667c16.042667 1.706667 25.258667 1.877333 40.618667 0.341333l90.965333 167.594667c2.218667 4.266667 6.656 6.826667 11.434667 6.826667 0 0 0 0 0.170667 0l0.512 0 0.170667 0 0.512 0c5.12-0.512 9.557333-3.754667 11.434667-8.704l30.890667-85.504 89.770667 20.821333C953.002667 906.24 958.122667 904.362667 961.194667 900.266667L961.194667 900.266667zM567.978667 871.424 567.978667 871.424l-13.824-38.912c-0.853333-2.218667-3.072-3.413333-5.290667-2.901333l-40.96 9.216 52.565333-94.378667c18.261333 18.602667 32.768 27.136 55.466667 39.594667L567.978667 871.424zM692.394667 744.96 692.394667 744.96c-68.778667-0.341333-124.586667-56.661333-124.245333-125.44 0.170667-68.608 55.978667-124.245333 124.757333-124.245333 0.170667 0 0.512 0 0.512 0 68.778667 0.341333 124.586667 56.32 124.245333 125.269333S761.344 744.96 692.394667 744.96zM839.68 842.752 839.68 842.752c-3.072-0.682667-5.973333 1.024-7.168 3.925333l-15.872 44.373333-54.954667-101.034667c25.941333-14.336 43.178667-24.576 64.341333-45.738667l60.245333 109.056L839.68 842.752 839.68 842.752z" p-id="4289" fill="#DFDFDF"></path><path d="M224.938667 213.504 224.938667 271.701333 682.496 271.701333 682.496 213.504Z" p-id="4290" fill="#DFDFDF"></path><path d="M815.104 52.736l-689.493333 0c-34.304 0-62.122667 28.842667-62.122667 64.170667l0 733.696c0 35.498667 27.989333 64.170667 62.122667 64.170667l245.76 0 0-58.026667L121.514667 856.746667 121.514667 110.592 819.2 110.592l0 280.576 58.026667 0L877.226667 116.906667C877.226667 81.408 849.237333 52.736 815.104 52.736L815.104 52.736z" p-id="4291" fill="#DFDFDF"></path><path d="M550.912 432.469333 550.912 374.272 224.938667 374.272 224.938667 432.469333Z" p-id="4292" fill="#DFDFDF"></path></svg>
            <el-button icon="Plus" class="upload_pic_btn_style">点击选择资质</el-button>
          </div>
          <div v-else class="scan-img">
            <upload-img v-model="form.attach" width="240" height="180" useScan iswatch></upload-img>
          </div>
        </div>
        <div class="btns">
          <!-- <el-button size="large" @click="doClose">返回</el-button> -->
          <el-button type="primary" size="large" @click="doPrevStep">上一步</el-button>
          <el-button type="primary" size="large" @click="doNextStep(false)">下一步</el-button>
          <el-button type="primary" size="large" @click="doNextStep(true)">保存</el-button>
        </div>
      </template>
    </el-card>

    <!-- 选择资质弹窗 -->
    <el-dialog v-model="show" title="选择资质" top="5vh" width="40%" center draggable @close="resetForm">
      <div class="search-box">
        <el-form :model="query" inline>
          <el-form-item label="资质名称:">
            <el-input v-model="query.name" placeholder="请输入资质名称" clearable/>
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
          <el-button icon="Plus" color="#FFB800" @click="doChoose">选择</el-button>
          <el-button icon="Upload" color="#FF5722" @click="innerShow = true">上传</el-button>
        </div>
      </div>
      <el-table ref="tableRef" :data="dataList" max-height="300" row-key="id" border>
        <el-table-column type="selection" align="center" width="100" />
        <el-table-column label="图片" align="center">
          <template #default="{row}">
            <div class="img-cell">
              <upload-img v-model="row.attach" width="40" height="40" useScan></upload-img>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="资质名称" prop="name" align="center"></el-table-column>
      </el-table>
      <el-pagination 
        class="paging"
        v-show="query.total"
        small
        layout="total, sizes, prev, pager, next, jumper" 
        :current-page="query.current" 
        :page-size="query.size"
        :total="query.total"
        @current-change="load"
        @size-change="sizeChange">
      </el-pagination>
      <el-dialog v-model="innerShow" title="新增资质" top="10vh" width="30%" center draggable append-to-body class="append-to-body-dialog">
        <el-form ref="formRef" :model="uploadForm" :rules="rules" size="default">
          <el-form-item label="资质名称" prop="name" required>
            <el-input v-model="uploadForm.name" placeholder="请输入资质名称" clearable style="width: 200px;"/>
          </el-form-item>
          <el-form-item label="资质上传" prop="attach" required>
            <upload-img v-model="uploadForm.attach" multiple></upload-img>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" size="default" @click="doSaveUploadCredential">保存</el-button>
          <el-button size="default" @click="innerShow = false">关闭</el-button>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup name="goodsCredential">
  import { saveGoodsCredentialRelevanceApi, getGoodsCredentialRelevanceApi, getGoodsCredentialsListPagesApi, cudGoodsCredentialApi } from '@/api/api'
  import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
  import { useStore } from 'vuex' 

  const store = useStore()
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  const formRef = ref(null)
  const tableRef = ref(null)
  const emits = defineEmits(['prevStep', 'nextStep', 'close'])
  defineExpose({init}) // 抛出组件方法供父组件使用

  const currentData = reactive({
    loading: false,
    show: false,
    innerShow: false,
    dataList: [],
    query: {
      name: '',
      merchantId: '',
      current: 1,
      size: 20,
      total: 0
    },
    form: {
      productId: '',
      merchantId: '',
      productCredId: '',
      attach: ''
    },
    uploadForm: {
      merchantId: '',
      name: '',
      attach: ''
    },
    rules: {
      name: [{ required: true, message: '请输入资质名称', trigger: ['blur', 'change'] }],
      attach: [{ required: true, message: '请上传商品资质', trigger: ['blur', 'change'] }]
    }
  })
  let {loading, show, innerShow, dataList, query, form, uploadForm, rules} = toRefs(currentData)

  // 初始化数据
  init()
  function init() {
    currentData.form.productId = store.state.productId
    if(currentData.form.productId) {
      getGoodsCredentialRelevanceApi(currentData.form.productId).then(res => {
        if(res.code === '200') {
          currentData.form.merchantId = res.data.merchantId || ''
          currentData.form.productCredId = res.data.productCredId || ''
          currentData.form.attach = res.data.attach || ''
        }
      })
    }
  }

  // 查询现有商品资质
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getGoodsCredentialsListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  function toChooseCredential() {
    currentData.query.name = ''
    currentData.query.merchantId = window.sessionStorage.getItem('merchantId')
    load(1)
    currentData.show = true
  }

  // 点击选择
  function doChoose() {
    let chooseAttachs = tableRef.value.getSelectionRows()
    if(!chooseAttachs.length) {
      currentThis.$message.error('请勾选商品资质')
      return
    } else if(chooseAttachs.length > 1) {
      currentThis.$message.error('只能选择一种资质')
      return
    } else {
      currentData.form.attach = chooseAttachs[0].attach
      currentData.show = false
    }
  }

  // 计算已选择的资质数量
  function getCredentialNum() {
    let arr = currentData.form.attach ? currentData.form.attach.split(',') : []
    return arr.length
  }

  // 保存新增资质
  function doSaveUploadCredential() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm(`确认新增吗？`).then(() => {
          let loading = currentThis.$loading(`正在新增`)
          currentData.uploadForm.merchantId = window.sessionStorage.getItem('merchantId')
          cudGoodsCredentialApi('save', currentData.uploadForm).then(res => {
            loading.close()
            if(res.code === '200') {
              load(1)
              currentData.innerShow = false
              currentThis.$message.success(res.message)
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  function resetForm() {
    tableRef.value.clearSelection()
  }

  // 关闭
  function doClose() {
    emits('close')
  } 

  // 上一步
  function doPrevStep() {
    emits('prevStep')
  }

  // 下一步/保存
  function doNextStep(type) {
    if(!currentData.form.attach) {
      currentThis.$message.error('请选择资质')
      return
    }
    currentData.form.productId = store.state.productId
    currentData.form.merchantId = window.sessionStorage.getItem('merchantId')
    if(type) {
      currentThis.$messageBox.confirm('确认保存吗？').then(() => {
        let loading = currentThis.$loading('正在保存，请耐心等待')
        saveGoodsCredentialRelevanceApi(currentData.form).then(res => {
          loading.close()
          if(res.code === '200') {
            currentThis.$message.success('保存成功')
            doClose()
          } else {
            currentThis.$message.error(res.message)
          }
        })
      }).catch(() => {})
    } else {
      saveGoodsCredentialRelevanceApi(currentData.form).then(res => {
        if(res.code === '200') {
          emits('nextStep')
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }
  }
</script>

<style lang="less" scoped>
.goodsCredential{
  :deep(.el-card){
    margin-bottom: 15px;
    .el-card__header{
      display: flex;
      align-items: center;
      .el-icon{
        margin-right: 5px;
      }
    }
    .el-card__body{
      padding: 20px 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      .upload_pic_btn_box{
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 15px;
      }
      .upload_pic_btn_style{
        border-color: #00B7EE !important;
        background-color: #00B7EE !important;
        color: #ffffff !important;
      }
      .upload_pic_number{
        color: #D90615;
      }
      .upload_pic_tips_box{
        width: calc(100% - 22px);
        padding: 0 10px;
        height: 500px;
        border: #E4E7ED dashed 1px;
        display: flex;
        align-items: center;
        justify-content: center;
        .upload_pic_tips{
          height: 160px;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          align-items: center;
        }
        .scan-img{
          width: 100%;
          height: 500px;
        }
      }
      .btns{
        margin-top: 30px;
        display: flex;
        justify-content: center;
      }
    }
  }
  :deep(.el-dialog){
    .search-box{
      display: flex;
      justify-content: space-between;
      >.search-btn{
        >.el-button{
          color: #ffffff !important;
        }
      }
    }
  }
}
</style>